package com.zxmc.server.controller.user;

import com.zxmc.common.constant.JwtClaimsConstant;
import com.zxmc.common.context.BaseContext;
import com.zxmc.common.properties.JwtProperties;
import com.zxmc.common.result.Result;
import com.zxmc.common.utils.JwtUtil;
import com.zxmc.pojo.dto.UserLoginDto;
import com.zxmc.pojo.entity.User;
import com.zxmc.pojo.vo.UserLoginVO;
import com.zxmc.server.service.UserService;
import com.zxmc.task.UserSessionManager;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user/user")
@Slf4j
@Api(tags = "用户接口")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private UserSessionManager userSessionManager;

    @GetMapping("/list")
    @ApiOperation("查询用户信息")
    public Result<User> list() {
        log.info("查询用户信息");
        return Result.success(userService.list());
    }
    @GetMapping("/listById")
    @ApiOperation("查询用户信息")
    public Result<User> list(Integer id) {
        log.info("查询用户信息,{}",id);
        return Result.success(userService.listById(id));
    }
    @PostMapping("/update")
    @ApiOperation("修改用户信息")
    public Result update(@RequestBody User user) {
        log.info("修改用户信息:{}", user);
        userService.update(user);
        return Result.success();
    }
    @PostMapping("/register")
    @ApiOperation("用户注册")
    public Result register(@RequestBody UserLoginDto userLoginDto) {
        log.info("注册信息:{}", userLoginDto);
        userService.register(userLoginDto);
        return Result.success();
    }

    @PostMapping("/login")
    @ApiOperation("用户登录")
    public Result<UserLoginVO> list(@RequestBody UserLoginDto userLoginDto) {
        log.info("用户信息:{}", userLoginDto);
        User user = userService.login(userLoginDto);
        userSessionManager.startTaskForUser(user.getId());
        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getId());

        String token = JwtUtil.createJWT(
                jwtProperties.getUserSecretKey(),
                jwtProperties.getUserTtl(),
                claims);

        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(user.getId())
                .username(user.getUsername())
                .token(token)
                .build();
        return Result.success(userLoginVO);
    }
    @GetMapping("/logout")
    @ApiOperation("用户登出")
    public Result logout()
    {
        log.info("用户登出{}", BaseContext.getCurrentId());
        userSessionManager.stopTaskForUser(BaseContext.getCurrentId());
//        userService.logout();
        return Result.success();
    }

}
